﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace FCS.Testing
{
    class UPDServer
    {
        static void Main(string[] args)
        {
            UdpClient u = new UdpClient(50000);
            //Console.Write("Enter IP address: ");

            String strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            IPAddress ipa = addr[3];
            Console.WriteLine("IP Address: " + ipa.ToString());

            Console.WriteLine("UDP Server");
            Console.WriteLine("Waiting for data");
            try
            {
                //array in which received data is placed
                byte[] recData;
                //create an IP endpoint for Receive() to populate
                IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 50001);

                while (true)
                {
                    //wait for data to come in
                    recData = u.Receive(ref ipe);

                    Console.WriteLine("Data received:");
                    for (int i = 0; i < recData.Length; i++)
                    {
                        Console.Write(recData[i] + " ");
                    }
                    Console.WriteLine();

                    //connect to localhost, port 50001
                    u.Connect(ipa, 50001);
                    //Console.WriteLine("Sending response");

                    byte[] sendData = { 0, 1, 2 };
                    u.Send(sendData, sendData.Length);

                    //Console.WriteLine("Response sent");

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
    }
}
